package com.chalk.config.rabbit;

import com.chalk.common.constant.CommonConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.RedisUtil;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.vo.MsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @date: 2019-05-07 下午 12:26
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
//@Component
public class RabbitMQProducer implements ConfirmCallback, RabbitTemplate.ReturnCallback {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ReturnCallBackListener returnCallBackListener;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 发送消息
     * @param message
     */
    public Result sendQueue(MsgBody message) {
        // 成功调用
        this.rabbitTemplate.setConfirmCallback(this);
        // 失败调用
        this.rabbitTemplate.setReturnCallback(this);
        try {
            CorrelationData data = new CorrelationData();
            data.setId(message.getKillItemId()+":"+message.getMemberId());
            this.rabbitTemplate.convertAndSend(RabbitConfig.KILL_QUEUE, message,data);
            logger.info("【send Queue已发送消息】");
            return Result.success(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(ResultCode.FAILURE);
        }
    }

    /**
     * 发布者成功发布消息到队列后执行
     * @param data 回调的相关数据
     * @param ack 对于ack是真的，对于nack是假的
     * @param cause nack的可选原因（如果可用），否则为null。
     */
    @Override
    public void confirm(CorrelationData data, boolean ack, String cause) {
        if(data != null){
            System.out.println("--------correlationData---------"+data.toString());
        }
        System.out.println("--------ack---------"+ack);

        if(ack){
            String[] split = data.getId().split(":");
            redisUtil.sAdd(CommonConstants.QUEUE_PRE_KILL+split[0],split[1]);
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("return--message:" + new String(message.getBody()) + ",replyCode:" + replyCode + ",replyText:" + replyText + ",exchange:" + exchange + ",routingKey:" + routingKey);
    }
}
